﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using NovelReader.Manager;

namespace NovelReader
{
    /// <summary>
    /// 主调用程序
    /// </summary>
    public class NovelDownloader
    {
        private static INovelManage managager;

        public NovelDownloader()
        {
            managager = new DBNovelManager();
        }

        /// <summary>
        /// 获得下载之后的文件列表
        /// </summary>
        /// <param name="novelName"></param>
        /// <returns></returns>
        /// <remarks>Deprecated</remarks>
        public List<string> GetDownLoadedLinks(string novelName)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(Path.Combine(CommonDef.BaseDir, novelName));

            if (dirInfo.Exists)
            {
                return (from file in dirInfo.GetFiles()
                        select file.Name).ToList<string>();
            }
            else
            {
                dirInfo.Create();

                return new List<string>();
            }
        }

        /// <summary>
        /// 更新小说
        /// </summary>
        /// <param name="novelName">小说名称</param>
        /// <param name="strUrl">小说链接地址</param>
        /// <returns>是否成功</returns>
        public bool UpdateNovel(string novelName, string strUrl)
        {
            var novelInfo = DownLoadNovel(strUrl);

            Novel novel = CommonDef.GetParser(strUrl).ExtractNovelCatelogLinks(strUrl, novelInfo.Content);

            novel.NovelName = novelName;

            managager.CheckNovel(novel);

            managager.DownLoadLinks(novel);

            return true;
        }

        /// <summary>
        /// 返回小说下载的结构体
        /// 里面包括下载的内容，下载的状态码
        /// </summary>
        /// <param name="strUrl">下载链接</param>
        /// <returns>NovelInfo</returns>
        public NovelInfo DownLoadNovel(string strUrl)
        {
            string strContent;

            WebRequest request = WebRequest.Create(strUrl);
            request.Credentials = CredentialCache.DefaultCredentials;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string strStatus = response.StatusDescription;
            HttpStatusCode hStatusCode = response.StatusCode;
            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding("GB2312")))
                {
                    strContent = reader.ReadToEnd();
                }
            }

            response.Close();

            NovelInfo info = new NovelInfo(strContent, strStatus, hStatusCode);
            return info;
        }
    }
}
